package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Description: 预约Controller
 * @Author: yp
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    /**
     * 查询预约信息
     *
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 预约
     *
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        try {
            //1.校验验证码(redis里面存的和用户输入的比较)

            String telephone = (String) map.get("telephone"); //获得手机号码
            String redisValidateCode = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone); //取出redis里面存的验证码
            String validateCode = (String) map.get("validateCode"); //获得用户输入验证码
            if(redisValidateCode == null || !redisValidateCode.equals(validateCode)){
                //校验失败
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            //2.调用业务, 进行预约, 响应
            Result result = orderService.submit(map);

            if(result.isFlag()){
                //预约成功,再发送一条短信,通知
                String orderDate = (String) map.get("orderDate");
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDER_FAIL);
        }
    }


}
